﻿using System;
using System.IO;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.Mvc;
using nanoCMS.Blog.WebUI.Models;
using nanoCMS.Blog.WebUI.Models.ViewModels;
using nanoCMS.Core;
using nanoCMS.Core.Extensions;
using nanoCMS.Core.Membership;

namespace nanoCMS.Blog.WebUI.Controllers
{

    public class BlogPostController : Controller
    {

        private readonly WorldContext worldContext;
        private BlogPostService blogPostService;

        public BlogPostController(WorldContext worldContext)
        {
            this.worldContext = worldContext;
            blogPostService = new BlogPostService(worldContext);
        }

        public ActionResult ShowBlogPost(int id)
        {
            BlogPostVM model = blogPostService.GetBlogPost(id);
            return PartialView(model);
        }


        [HttpGet]
        public ActionResult ListBlogPosts(int categoryID, string elementKey)
        {
            var model = blogPostService.ListBlogPosts(categoryID);
            ViewBag.ElementKey = elementKey;

            return PartialView("ListBlogPosts", model);
        }

        #region Administration
        [HttpGet]
        public ActionResult Create(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("EditBlogPost", blogPostService.CreateEmptyEditBlogPostVM());
        }

        [HttpGet]
        public ActionResult Edit(int id, string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("EditBlogPost", blogPostService.GetEditBlogPostVM(id));
        }

        [HttpPost]
        public ActionResult Save(BlogPostVM blogPostModel, int[] BlogInCategories, string returnUrl)
        {
            if(!blogPostService.CheckCategories(BlogInCategories))
            {
                ModelState.AddModelError("BlogCategories", "No categories selected!"); // TODO langugae
            }
            if (ModelState.IsValid)
            {
                returnUrl = HttpUtility.UrlDecode(returnUrl);
                string location = returnUrl; 
                // TODO srediti redirectove (na... ShowBlogPost ? )
                if(blogPostModel.BlogPostID == 0)
                {
                    BlogPostVM newBlogPost = blogPostService.Add(blogPostModel, BlogInCategories);
                    location = Url.Action("ShowBlogPost", "BlogPost", new { area = "Blog", id = newBlogPost.BlogPostID }); 
                }
                else
                {
                    blogPostService.Edit(blogPostModel, BlogInCategories);
                    location = Url.Action("ShowBlogPost", "BlogPost", new { area = "Blog", id = blogPostModel.BlogPostID }); 
                }
                return Json(new { status = "redirect", location });
            }
            return PartialView("ValidationSummary");
        }

        [HttpPost]
        public ActionResult UploadImage(int? chunk, string name)
        {
            try
            {
                if (!chunk.HasValue)
                {
                    HttpPostedFileBase uploadedFile = Request.Files[0];
                    // check uploaded file
                    if (uploadedFile == null)
                    {
                        throw new Exception("Error during upload.");
                    }
                    // process image
                    Image image = Image.FromStream(uploadedFile.InputStream);
                    // store image to disk
                    string imageDestination = Server.MapPath(Settings.ImageUploadPath +
                        RequestItems.TenantID  + "/Blog/Uploads/");
                    // check dir
                    DirectoryInfo dir = new DirectoryInfo(imageDestination);
                    if(!dir.Exists)
                    {
                        dir.Create();
                    }
                    // cerate file name & final upload path
                    string newFileName = Guid.NewGuid() + ".png"; 
                    string uploadPath = Path.Combine(imageDestination, newFileName);
                    image.Save(uploadPath, ImageFormat.Png);
                    string webUrl = Url.Content(Settings.ImageUploadPath) + RequestItems.TenantID  + "/Blog/Uploads/"; 
                    // return uploaded filename (URL)
                    string returnFileName = newFileName + "?newGuid=" + Guid.NewGuid();
                    var result = new { result = "ok", imageUrl = webUrl + returnFileName };
                    return Json(result);
                }
                else
                {
                    throw new Exception("Chunking not supported!");
                }
            }
            catch (Exception e)
            {
                return Json(new { result = "error", message = e.Message });
            }
        }
        #endregion
    }       
}
